import loginService from '@/api/loginService'
import type {
  IMloginParams,
  ISmsLoginParams,
} from '@/api/model/loginModel'
import type { IUser } from '@/api/model/sysUserModel'
import env from '@/config/env'

interface IState {
  token: string
  userInfo: IUser | null
  isVip: string
  token_type:string
  refresh_token:string
  code:string

}

export default defineStore({
  id: 'user',
  state: (): IState => {
    return {
      token: '',
      userInfo: null,
      isVip: '',
      token_type:'',
      refresh_token:'',
      code:''
    }
  },
  getters: {
    userId: state => state.userInfo?.id,
    nickname: state =>
      state?.userInfo?.realname
        ? state?.userInfo?.realname
        : state.userInfo?.username,
    avatar: state =>
      state.userInfo?.avatar ? `${state.userInfo.avatar}` : '',
    bgImg: state =>
      state.userInfo?.bgImg ? `${env.cos}${state.userInfo.bgImg}` : '',
    description: state => state.userInfo?.description,
  },
  actions: {

    /**
     * 账号登录
     */
    async accountLogin(params: IMloginParams) {
      const loginRes = await loginService.mLogin(params)
      if (loginRes.access_token) {

        this.token = loginRes.access_token
        this.userInfo = loginRes.userInfo
        this.refresh_token= loginRes.refresh_token
        this.token_type = loginRes.token_type
      }
      return loginRes
    },

    /**
     * 验证码登录
     */
    async codeLogin(params: ISmsLoginParams) {
      const loginRes = await loginService.smsLogin(params)
      if (loginRes.access_token) {
        this.token = loginRes.access_token
        this.userInfo = loginRes.userInfo
        this.refresh_token= loginRes.refresh_token
        this.token_type = loginRes.token_type
      }
      return loginRes
    },
   
    /**
     * 退出登录
     */
    async logout() {
      uni.showLoading({ mask: true })
      try {
        // 请求
        await loginService.logout(this.token)
      } catch (e) {
        console.error(e)
      }

      // 重置所有store
      this.$reset()
      uni.reLaunch({
        url: `/subPackages_login/index/index`,
      })
      uni.hideLoading()
    },
  },
  persist: {
    enabled: true,
  },
})
